package cn.ljy.mes.service.impl;

import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.mes.dao.mapper.MesCarBrandMapper;
import cn.ljy.mes.dao.mapper.MesCarModelMapper;
import cn.ljy.mes.dao.mapper.MesMaterialMapper;
import cn.ljy.mes.model.MesCarBrand;
import cn.ljy.mes.model.query.MesCarBrandQuery;
import cn.ljy.mes.model.query.MesCarModelQuery;
import cn.ljy.mes.service.MesCarBrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.Serializable;
import java.util.List;

@Service
//@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Validated//表示开启sprint的校检框架，会自动扫描方法里的@Valid（@Valid注解一般写在接口即可）
@Slf4j
public class IMesCarBrandService extends IBaseService<MesCarBrand, MesCarBrandQuery> implements MesCarBrandService {
    @Autowired
    private MesCarBrandMapper mapper;
    @Autowired
    private MesMaterialMapper mesMaterialMapper;
    @Autowired
    private MesCarModelMapper mesCarModelMapper;

    //设置关联属性
    private void setParam(MesCarBrand mesCarBrand){
        if(mesCarBrand!=null){
            //车型数量
            MesCarModelQuery carModelQuery=new MesCarModelQuery();
            carModelQuery.setCarBrand(mesCarBrand);
            mesCarBrand.setCarModelNumber(mesCarModelMapper.count(carModelQuery));
        }
    }

    @Override
    public void afterFindAll(List<MesCarBrand> list) {
        for(MesCarBrand mesCarBrand:list){
            //添加相关关联属性
            this.setParam(mesCarBrand);
        }
    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        for(Serializable id:ids){
            //检查是否有车型调用本品牌
            MesCarModelQuery carModelQuery=new MesCarModelQuery();
            carModelQuery.setCarBrand(new MesCarBrand((Long.valueOf(id.toString()))));
            int carModelNumber=mesCarModelMapper.count(carModelQuery);
            if(carModelNumber>0){
                MesCarBrand carBrand=mapper.findByIdNoRelation(id);
                throw new MyServiceException("删除失败："+carBrand.getName()+"下还有"+carModelNumber+"个车型，请先移除或转移这些车型再执行删除");
            }
        }
    }
}
